//
//  WBHomeViewModel.swift
//  Weibo
//
//  Created by 汪博文 on 2016/11/17.
//  Copyright © 2016年 Wbw. All rights reserved.
//
//1.将控制器的网络请求方法封装到 视图模型中
//2.将数据处理成模型数据
import UIKit

class WBHomeViewModel: NSObject {
    //懒加载数据属性
    lazy var viewModelArray: [WBStatusViewModel] = [WBStatusViewModel]()
    
    //获取首页数据,不负责和UI几面打交道,用闭包回调数据
    func loadData(finished: @escaping (Bool) -> ()) {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let parameters = ["access_token" : WBUserAccountViewModel.shared.access_token]
        HMNetworkTools.shared.request(method: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
            if error != nil {
                return
            }
            //print(responseObject)
            //解析数据转换为模型数据
            let dict = responseObject as! [String : Any]
            //从字典中取出一个数组 尝试转换成字典数组 判断转换是否成功 不成功返回
            guard let array = dict["statuses"] as? [[String : Any]] else {
                //SVProgressHUD.showError(withStatus: errorString)
                return
            }
            //print(array)
            //遍历数组 字典转模型
            var tempArray = [WBStatusViewModel]()
            //tempArray = NSArray.yy_modelArray(with: WBStatus.self, json: array) as! [WBStatus]
            for item in array {
                let viewModel = WBStatusViewModel()
                let status = WBStatus()
                //调用YYModel方法来字典转模型
                status.yy_modelSet(with: item)
                //给viewModel的status
                viewModel.status = status
                //添加到一个临时数组中 获取数据都是按页一次获取20条数据
                tempArray.append(viewModel)
            }
            //执行成功的回调
            self.viewModelArray = tempArray
            finished(true)
        }
    }
}
